<?php

require_once('functions/pageLoad.php');

//Change By Vyas Ishan 14 May 2013 task1
$page_title = 'Register';
$city = '';
$terms = '';
if ( array_key_exists('city',$_POST) )  {
	$city = $_POST['city'];
}
if ( array_key_exists('terms',$_POST) )  {
	$terms = $_POST['terms'];
}
//Change By Vyas Ishan 14 May 2013 task1

if($_SERVER['REQUEST_METHOD'] == 'POST' && $_POST['form'] == 'register'){

//$resp = recaptcha_check_answer ($privatekey, $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]);

$fail = '';

$email_regex = "/^[^@]+@([-\w]+\.)+[A-Za-z]{2,4}$/i";
$postcode_regex = "/^([A-PR-UWYZa-pr-uwyz]([0-9]{1,2}|([A-HK-Ya-hk-y][0-9]|[A-HK-Ya-hk-y][0-9]([0-9]|[ABEHMNPRV-Yabehmnprv-y]))|[0-9][A-HJKS-UWa-hjks-uw])\ {0,1}[0-9][ABD-HJLNP-UW-Zabd-hjlnp-uw-z]{2}|([Gg][Ii][Rr]\ 0[Aa][Aa])|([Ss][Aa][Nn]\ {0,1}[Tt][Aa]1)|([Bb][Ff][Pp][Oo]\ {0,1}([Cc]\/[Oo]\ )?[0-9]{1,4})|(([Aa][Ss][Cc][Nn]|[Bb][Bb][Nn][Dd]|[BFSbfs][Ii][Qq][Qq]|[Pp][Cc][Rr][Nn]|[Ss][Tt][Hh][Ll]|[Tt][Dd][Cc][Uu]|[Tt][Kk][Cc][Aa])\ {0,1}1[Zz][Zz]))$/i";

// check email

	$sql = "SELECT id FROM users WHERE email = '".mysql_real_escape_string($_POST['email1'])."'";
	$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());
	$rows=mysql_num_rows($query);
	
//Change By Vyas Ishan 14 May 2013 Task1
#$fail.= (strlen($_POST['firstname']) == 0 || strlen($_POST['surname']) == 0) ? '<li>Name was not entered</li>' : '';
$fail.= (strlen($_POST['firstname']) == 0) ? '<li>Name was not entered</li>' : '';

$fail.= (strlen($_POST['telephone']) == 0) ? '<li>Telephone number not entered</li>' : '';
$fail.= (strlen($_POST['telephone']) > 0 && !ctype_digit(str_replace(" ", "", $_POST['telephone']))) ? '<li>Invalid telephone number entered, please use numbers only</li>' : '';
$fail.= (preg_match($email_regex, $_POST['email1']) == 0) ? '<li>Invalid email address entered</li>' : '';

//Change By Vyas Ishan 14 May 2013 Task1
#$fail.= ($_POST['email1'] != $_POST['email2']) ? '<li>Email addresses do not match</li>' : '';

$fail.= ($rows > 0) ? '<li>An account already exists with that email address</li>' : '';
$fail.= (strlen($_POST['password1']) < 6 || strlen($_POST['password1']) > 16) ? '<li>Passwords must be 6-16 characters long</li>' : '';

//Change By Vyas Ishan 14 May 2013 task1
#$fail.= ($_POST['password1'] != $_POST['password2']) ? '<li>Passwords do not match</li>' : '';
$fail.= (strlen($_POST['line_1']) == 0) ? '<li>Address was not entered</li>' : '';
$fail.= (strlen($_POST['city']) == 0) ? '<li>City was not entered</li>' : '';

//Change By Vyas Ishan 14 May 2013 task1 Regular exp is currently commented and need to be asked
$fail.= (strlen($_POST['postcode']) == 0) ? '<li>Postcode was not entered</li>' : '';
#$fail.= (preg_match($postcode_regex, str_replace(" ", "", $_POST['postcode'])) == 0) ? '<li>Invalid postcode entered</li>' : '';

//Change By Vyas Ishan 14 May 2013 task1
#$fail.= ($_POST['terms'] != '1') ? '<li>You must agree to the terms of use</li>' : '';
$fail.= ($_POST['terms'] != 'terms') ? '<li>You must agree to the terms of use</li>' : '';
$fail.= (strlen($_POST['name']) > 0) ? '<li>Please leave the top text field blank.</li>' : '';

if(strlen($fail) > 0){

// PHAIL

$results = '<h1>Registration error!</h1><p>Please correct the following errors;</p><ul>'.$fail.'</ul>';

}

else
{

// FINE - INSERT, SEND EMAIL AND REDIRECT

	require("classes/class.phpmailer.php");
	$mail = new PHPMailer();
	$mail->IsSMTP(); // telling the class to use SMTP
	$mail->Host = "localhost"; // SMTP server
	$mail->From = $settings['no_reply_email'];
	$mail->FromName = "I Want A Tradesman";

	$mail->AddAddress($_POST['email1']);

	$mail->Subject = "Welcome to I Want A Tradesman!";
	$mail->Body = "Dear ".$_POST['firstname']." ".$_POST['surname']."\r\n\r\nWelcome to I Want A Tradesman. Thanks for registering!\r\n\r\nE-mail address: ".$_POST['email1']."\r\n\r\nYour account has been created and you can now sign in to:\r\n\r\n-	Post jobs\r\n-	View quotes\r\n-	Leave feedback\r\n\r\nIf you have any enquiries, please do not hesitate to e-mail us on ".$settings['site_email'].".\r\n\r\nKind regards\r\n\r\nThe I Want A Tradesman Team\r\n\r\n\r\nThis email and any files transmitted with it are confidential and intended solely for the use of the individual or entity to whom they are addressed. This message contains confidential information and is intended only for the individual named. If you are not the named addressee you should not disseminate, distribute or copy this e-mail. Please notify the sender immediately by e-mail if you have received this e-mail by mistake and delete this e-mail from your system. If you are not the intended recipient you are notified that disclosing, copying, distributing or taking any action in reliance on the contents of this information is strictly prohibited.";

	$mail->Send();

	
	//Change By Vyas Ishan 14 May 2013 Task1
	$surName = '';
	if (array_key_exists('surname',$_POST)) {
		$surName = mysql_real_escape_string(stripslashes($_POST['surname']));
	}
	
	// insert user, email has sent and does not already exist in db
	$sql="INSERT INTO users (email, firstname, surname, telephone, mobile, newsletter, member_since, last_login) VALUES ('".mysql_real_escape_string(stripslashes($_POST['email1']))."', '".mysql_real_escape_string(stripslashes($_POST['firstname']))."', '".$surName."', '".mysql_real_escape_string(str_replace(" ", "", $_POST['telephone']))."', '".mysql_real_escape_string(str_replace(" ", "", $_POST['mobile']))."', '".mysql_real_escape_string($_POST['newsletter'])."', '".date("Y-m-d H:i:s")."', '".date("Y-m-d H:i:s")."')";
	$query=mysql_query( $sql ) or die ("Error in query: $sql. " . mysql_error());
	$user_id = mysql_insert_id();

	// free sms

	$sql="INSERT INTO SMS (user_id, sms_remaining) VALUES ('".$user_id."', '1000')";
	$query=mysql_query( $sql ) or die ("Error in query: $sql. " . mysql_error());

	// encrypt password

	$encrypt1 = base64_encode($_POST['password1'].'_'.$encryption_salt);
	$encrypt2 = md5($encrypt1.'_'.$_POST['email1'].'_'.$encryption_salt);

	// add address

	// google map

	$address = $_POST['line_1'].",".$_POST['line_2'].",".$_POST['line_3'].",".$_POST['postcode'];
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "http://maps.google.com/maps/geo?q=".urlencode($address)."&output=csv&oe=utf8&sensor=false&key=".$settings['google_api_key']);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($ch);
        curl_close($ch);
	$outputArr = explode(",",$output);

	$sql="INSERT INTO addresses (user_id, area_id, line_1, line_2, line_3, postcode, longitude, latitude) VALUES ('".$user_id."', '".mysql_real_escape_string($_POST['city'])."', '".mysql_real_escape_string(stripslashes($_POST['line_1']))."', '".mysql_real_escape_string(stripslashes($_POST['line_2']))."', '".mysql_real_escape_string(stripslashes($_POST['line_3']))."', '".mysql_real_escape_string(strtoupper($_POST['postcode']))."', '".$outputArr[3]."', '".$outputArr[2]."')";
	$query=mysql_query( $sql ) or die ("Error in query: $sql. " . mysql_error());
	$address_id = mysql_insert_id();

	// update user

	$userUpdate="UPDATE users SET address_id = '".$address_id."', password = '".$encrypt2."' WHERE id = '".$user_id."'";
	$userResult=mysql_query( $userUpdate ) or die ("Error in query: $userUpdate . " . mysql_error());

	$_SESSION['user'] = $user_id.'_'.$_SERVER['REMOTE_ADDR'];

	header("Location: /my-account");

}

}

else{
$results = '<h1>Register your free account</h1>';
}

include('includes/meta.php');
include('includes/header.php');
include('includes/navigation.php');

?>

<h1>You're one step away from a competitive online quote!</h1>

<?php echo $results; ?>

<div id="error_div" style="display: none;"></div>

<p>Please complete the form below to register for an account with us. There are no charges for posting or quoting jobs and your details are 100% secure. Tradesmen will not see any of your contact information until you personally accept a quote from them. Please view our <a href="/privacy">privacy policy</a> for more information.</p>

<p><strong>Note: If you're a tradesman or company please complete the <a href="/register-my-business">business registration form</a>.</strong></p>

<form method="post" action="/register.php" id="registerfrm" autocomplete="off">

<input type="hidden" id="form" name="form" value="register" style="display: none;" />
<input type="text" name="name" id="hideThis" class="textbox" value="<?php echo $_POST['name']; ?>" />

<div id="registration_form">

<div id="name_wrap">

<div class="rowWrapper" id="firstname_wrap">
<div class="rowLeft"><label for="firstname">First name:</label></div>
<div class="rowRight"><input type="text" name="firstname" id="firstname" class="textbox" value="<?php echo $_POST['firstname']; ?>" /></div>
</div>

<?php /*//Change By Vyas Ishan 14 May 2013 Task1?>
<div class="rowWrapper" id="surname_wrap">
<div class="rowLeft"><label for="surname">Surname:</label></div>
<div class="rowRight"><input type="text" name="surname" id="surname" class="textbox" value="<?php echo $_POST['surname']; ?>" /></div>
</div>
<?php */?>
</div>

<div id="number_wrap">

<div class="rowWrapper" id="telephone_wrap">
<div class="rowLeft"><label for="telephone">Telephone:</label></div>
<div class="rowRight"><input type="text" name="telephone" id="telephone" class="textbox" value="<?php echo $_POST['telephone']; ?>" placeholder="Enter at least one contact telephone number for tradesmen to contact you on." /></div>
</div>

<div class="rowWrapper" id="mobile_wrap">
<div class="rowLeft"><label for="mobile">Mobile:</label></div>
<div class="rowRight"><input type="text" name="mobile" id="mobile" class="textbox" value="<?php echo $_POST['mobile']; ?>" /></div>
</div>

</div>

<div id="email_wrap">

<div class="rowWrapper" id="email1_wrap">
<div class="rowLeft"><label for="email1">Email address:</label></div>
<div class="rowRight"><input type="text" name="email1" id="email1" class="textbox" value="<?php echo $_POST['email1']; ?>" placeholder="Enter your email address to receive your login details. Your details are safe." /></div>
</div>

<?php /*//Change By Vyas Ishan 14 May 2013 Task1?>
<div class="rowWrapper" id="email2_wrap">
<div class="rowLeft"><label for="email2">Confirm email:</label></div>
<div class="rowRight"><input type="text" name="email2" id="email2" class="textbox" value="<?php echo $_POST['email2']; ?>" /></div>
</div>
<?php */?>
</div>

<div id="password_wrap">

<div class="rowWrapper" id="password1_wrap">
<div class="rowLeft"><label for="password1">Password:</label></div>
<div class="rowRight"><input type="password" name="password1" id="password1" class="textbox" placeholder="Please enter a password 6-16 characters long." /></div>
</div>

<?php /*//Change By Vyas Ishan 14 May 2013 Task1?>
<div class="rowWrapper" id="password2_wrap">
<div class="rowLeft"><label for="password2">Confirm:</label></div>
<div class="rowRight"><input type="password" name="password2" id="password2" class="textbox" placeholder="Please confirm your password" /></div>
</div>
<?php */?>

</div>


<div id="address_wrap">

<div class="rowWrapper" id="line_1_wrap">
<div class="rowLeft"><label for="line_1">Address line 1:</label></div>
<div class="rowRight"><input type="text" name="line_1" id="line_1" class="textbox" value="<?php echo $_POST['line_1']; ?>" placeholder="Enter your address so that we can locate tradesmen that are local to your area." /></div>
</div>

<div class="rowWrapper" id="line_2_wrap">
<div class="rowLeft"><label for="line_2">Address line 2:</label></div>
<div class="rowRight"><input type="text" name="line_2" id="line_2" class="textbox" value="<?php echo $_POST['line_2']; ?>" /></div>
</div>

<div class="rowWrapper" id="line_3_wrap">
<div class="rowLeft"><label for="line_3">Address line 3:</label></div>
<div class="rowRight"><input type="text" name="line_3" id="line_3" class="textbox" value="<?php echo $_POST['line_3']; ?>" /></div>
</div>

<div class="rowWrapper" id="city_wrap">
<div class="rowLeft"><label for="city">Town/City:</label></div>
<div class="rowRight">

<?php
	// load areas
	$sql = "SELECT id, area FROM areas ORDER BY area";
	$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());

	$area_dropdown = '<select name="city" id="city"><option value="">Please select</option>';
	while($rs=mysql_fetch_assoc($query)){
	$selected =  ($city == $rs['id']) ? "selected" : "";
	$area_dropdown.= '<option  '.$selected.'  value="'.$rs['id'].'">'.htmlspecialchars($rs['area']).'</option>';
	}
	
	
	$area_dropdown.= '</select>';
?>
<?php echo $area_dropdown; ?>
</div>
</div>

<div class="rowWrapper" id="postcode_wrap">
<div class="rowLeft"><label for="postcode">Postcode:</label></div>
<div class="rowRight"><input type="text" name="postcode" id="postcode" class="textbox" value="<?php echo $_POST['postcode']; ?>" style="width: 80px;" /></div>
</div>

</div>

<div class="rowWrapper">
<div class="rowLeft">&nbsp;</div>
<div class="rowRight"><input type="checkbox" name="newsletter" id="newsletter"> <label for="newsletter">Yes, I would like to receive the weekly newsletter from I Want A Tradesman.</label></div>
</div>

<div class="rowWrapper">
<div class="rowLeft">&nbsp;</div>
<div class="rowRight">

<input type="checkbox"  <?php echo ($terms == 'terms') ? "checked" : "";?> value="terms" name="terms" id="terms"> <label for="terms">I confirm I have read and agreed to the <a href="#">terms of use</a> and <a href="#">privacy policy</a>.</label></div>
</div>

<div class="rowWrapper">
<div class="rowLeft">&nbsp;</div>
<div class="rowRight">

<?php /*?>
<script type="text/javascript">document.write('<'+'a onclick="return formval(\'register\');" style="cursor: pointer;"><'+'img src="/images/register_button.gif" alt="Register" /><'+'/a>');</script>
<noscript><input type="submit" value="Register" class="blue_submit_button" /></noscript>
<?php */?>
<input type="image" src="/images/register_button.gif" alt="Register">
</div>
</div>

</div>

</form>

<div style="display: none;"><img src="images/tick.png" alt="" /><img src="images/cross.png" alt="" /></div>

<?php 

include('includes/rightColumn.php');
include('includes/footer.php');

?>